package com.lianmai.chaincard.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.widget.Toast;

import com.lianmai.chaincard.MyApplication;
import com.lianmai.chaincard.R;
import com.lianmai.chaincard.utils.KeyBoardUtil;
import com.youth.xframe.utils.XDensityUtils;


/**
 * 搜索框
 */
public class SearchEditText extends android.support.v7.widget.AppCompatEditText implements View.OnFocusChangeListener, TextView.OnEditorActionListener, TextWatcher {
    private static final String TAG = "SearchEditText";
    /**
     * 图标是否默认在左边
     */
    private boolean isIconLeft = false;
    /**
     * 是否点击软键盘搜索
     */
    private boolean pressSearch = false;
    /**
     * 软键盘搜索键监听
     */
    private OnSearchClickListener onSearchClickListener;
    private OnFocusClickListener onFocusClickListener;
    private OnClearClickListener onClearClickListener;

    private Drawable[] drawables; // 控件的图片资源
    private Drawable drawableLeft, drawableDel; // 搜索图标和删除按钮图标
    private Rect rect; // 控件区域

    public void setOnSearchClickListener(OnSearchClickListener listener) {
        this.onSearchClickListener = listener;
    }

    public interface OnSearchClickListener {
        void onSearchClick(View view);
    }

    public void setOnFocusClickListener(OnFocusClickListener listener) {
        this.onFocusClickListener = listener;
    }

    public interface OnFocusClickListener {
        void onFocusClick(boolean isFocus);
    }

    public void setOnClearClickListener(OnClearClickListener listener) {
        this.onClearClickListener = listener;
    }

    public interface OnClearClickListener {
        void onClearClick();
    }

    public SearchEditText(Context context) {
        this(context, null);
        init();
    }

    public SearchEditText(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.editTextStyle);
        init();
    }


    public SearchEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    private void init() {
        setOnFocusChangeListener(this);
        setOnEditorActionListener(this);
        addTextChangedListener(this);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (isIconLeft) { // 如果是默认样式，直接绘制
            if (length() < 1) {
                drawableDel = null;
            }
            this.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, drawableDel, null);
            super.onDraw(canvas);
        } else { // 如果不是默认样式，需要将图标绘制在中间
            if (drawables == null) drawables = getCompoundDrawables();
            if (drawableLeft == null) drawableLeft = drawables[0];
            float textWidth = getPaint().measureText(getHint().toString());
            int drawablePadding = getCompoundDrawablePadding();
            int drawableWidth = drawableLeft.getIntrinsicWidth();
            float bodyWidth = textWidth + drawableWidth + drawablePadding;
            canvas.translate((getWidth() - bodyWidth - getPaddingLeft() - getPaddingRight()) / 2, 0);
            super.onDraw(canvas);
        }
    }


    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        // 被点击时，恢复默认样式
        if (!pressSearch && TextUtils.isEmpty(getText().toString())) {
            isIconLeft = hasFocus;
            if (onFocusClickListener != null) {
                onFocusClickListener.onFocusClick(isIconLeft);
            }
        }
    }

    @Override
    public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
        pressSearch = (i == EditorInfo.IME_ACTION_SEARCH);
        if (pressSearch && onSearchClickListener != null) {
            if (TextUtils.isEmpty(getText().toString())) {
                Toast.makeText(MyApplication.getInstance(), "请输入要搜索的内容!", Toast.LENGTH_SHORT).show();
                return true;
            } else {
                KeyBoardUtil.closeKeyboard(this, getContext());
                onSearchClickListener.onSearchClick(textView);
            }
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 清空edit内容
        int eventX;
        int eventY;
        if (drawableDel != null && event.getAction() == MotionEvent.ACTION_UP) {
            eventX = (int) event.getRawX();
            eventY = (int) event.getRawY();
            if (rect == null) rect = new Rect();
            getGlobalVisibleRect(rect);
            rect.left = rect.right - drawableDel.getIntrinsicWidth() -  XDensityUtils.dp2px(16);
            if (rect.contains(eventX, eventY)) {
                setText("");
                if (onClearClickListener != null) {
                    onClearClickListener.onClearClick();
                }
            }
        }
        // 删除按钮被按下时改变图标样式
        if (drawableDel != null && event.getAction() == MotionEvent.ACTION_DOWN) {
            eventX = (int) event.getRawX();
            eventY = (int) event.getRawY();
            if (rect == null) rect = new Rect();
            getGlobalVisibleRect(rect);
            rect.left = rect.right - drawableDel.getIntrinsicWidth();
            if (rect.contains(eventX, eventY))
                drawableDel = this.getResources().getDrawable(R.drawable.dialog_phone_delete_selector);
        } else {
            drawableDel = this.getResources().getDrawable(R.drawable.dialog_phone_delete_selector);
        }
        return super.onTouchEvent(event);
    }


    @Override
    public void afterTextChanged(Editable arg0) {
        if (this.length() < 1) {
            drawableDel = null;
            if (onClearClickListener != null) {
                onClearClickListener.onClearClick();
            }
        } else {
            drawableDel = this.getResources().getDrawable(R.drawable.dialog_phone_delete_selector);
        }
    }


    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                  int arg3) {
    }

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                              int arg3) {
    }

    public void setIconLeft(boolean isIconLeft, boolean pressSearch) {
        this.isIconLeft = isIconLeft;
        this.pressSearch = pressSearch;
        postInvalidate();
    }
}
